package edu.sfsu.powerrangers.jeopardy.editor;

import java.awt.FileDialog;
import java.awt.Frame;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import edu.sfsu.powerrangers.jeopardy.gamestate.Game;

public class EditorFrame extends JFrame {
	private static final long serialVersionUID = 1L;
	
	private GamePanel gp;
	private File file;
	
	public EditorFrame() {
		super("Untitled");
		gp = new GamePanel(1, 5, 6, false);
		gp.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));
		setContentPane(gp);
		file = null;
		
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setJMenuBar(new EditorMenuBar(this));
		pack();
		setLocationRelativeTo(null);
	}
	
	public EditorFrame(File f) {
		super(f.getName());
		gp = new GamePanel(1, 5, 6, false);
		Game[] games = new GameReader().readGames(f);
		if (games.length > 0) {
			gp.setGame(games[0]);
		}
		gp.setBorder(BorderFactory.createEmptyBorder(16, 16, 16, 16));
		setContentPane(gp);
		file = f;
		
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setJMenuBar(new EditorMenuBar(this));
		pack();
		setLocationRelativeTo(null);
	}
	
	public void save() {
		if (file == null) {
			FileDialog fd = new FileDialog(new Frame(), "Save File", FileDialog.SAVE);
			fd.setVisible(true);
			if (fd.getFile() != null) {
				file = new File(fd.getDirectory()+System.getProperty("file.separator")+fd.getFile());
				setTitle(file.getName());
			}
		}
		if (file != null) {
			new GameWriter().writeGames(file, new Game[]{ gp.getGame() });
		}
	}
	
	public void saveAs() {
		FileDialog fd = new FileDialog(new Frame(), "Save File", FileDialog.SAVE);
		fd.setVisible(true);
		if (fd.getFile() != null) {
			file = new File(fd.getDirectory()+System.getProperty("file.separator")+fd.getFile());
			setTitle(file.getName());
			new GameWriter().writeGames(file, new Game[]{ gp.getGame() });
		}
	}
	
	public void revert() {
		if (file != null) {
			Game[] games = new GameReader().readGames(file);
			if (games.length > 0) {
				gp.setGame(games[0]);
			}
		}
	}
}
